from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends, HTTPException, status
from datetime import datetime, timedelta
import logging

from app import crud
from app.models import schemas
from app.core import security
from app.core.user_database import get_user_db
from app.core.config import settings

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/login", response_model=schemas.LoginResponse)
async def login(
        login_data: schemas.UserLogin,
        db: AsyncSession = Depends(get_user_db)  # 使用异步会话
):
    try:
        username = login_data.username
        password = login_data.password

        logger.info(f"尝试登录用户: {username}")

        # 认证用户 - 使用异步查询
        user = await crud.authenticate_user(db, username, password)  # 添加await
        if not user:
            logger.warning(f"用户认证失败: {username}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )

        logger.info(f"用户认证成功: {user.username}")

        # 创建访问令牌
        access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = security.create_access_token(
            data={"sub": user.username}, expires_delta=access_token_expires
        )

        # 创建刷新令牌
        refresh_token_expires = timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
        refresh_token = security.create_refresh_token(
            data={"sub": user.username}, expires_delta=refresh_token_expires
        )

        # 计算过期时间
        expires = datetime.utcnow() + access_token_expires

        # 准备用户数据
        user_data = {
            "id": user.id,
            "username": user.username,
            "nickname": user.nickname,
            "avatar": user.avatar,
            "roles": user.roles.split(",") if user.roles else [],
            "permissions": user.permissions.split(",") if user.permissions else [],
            "is_active": user.is_active
        }

        return {
            "success": True,
            "data": user_data,
            "accessToken": access_token,
            "refreshToken": refresh_token,
            "expires": expires.strftime("%Y/%m/%d %H:%M:%S")
        }

    except HTTPException:
        # 已知异常直接抛出
        raise
    except Exception as e:
        logger.exception(f"登录过程中发生错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )